<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate" />
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="名称" prop="name" align="center">
        <template slot-scope="scope">
          <a :href="`${SiteSettings.siteWebUrl}/category/${scope.row.slug}`" :title="scope.row.name"><span>{{ scope.row.name }}</span></a>
        </template>
      </el-table-column>
      <el-table-column label="英文名称" prop="slug" align="center">
        <template slot-scope="scope">
          <a :href="`${SiteSettings.siteWebUrl}/category/${scope.row.slug}`" :title="scope.row.slug"><span>{{ scope.row.slug }}</span></a>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="description" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图标" prop="icon" align="center">
        <template slot-scope="scope">
          <i :class="scope.row.icon">{{ scope.row.icon }}</i>
        </template>
      </el-table-column>
      <el-table-column label="文章数" prop="count" align="center">
        <template slot-scope="scope">
          <i :class="scope.row.count">{{ scope.row.count }}</i>
        </template>
      </el-table-column>
      <el-table-column label="封面" prop="background" align="center">
        <template slot-scope="scope">
          <img style="width: 90px;height: 90px;" v-if="scope.row.background != null" :src="scope.row.background"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            <i class="fa fa-pencil fa-fw" />
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            <i class="fa fa-trash-o fa-lg" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="英文名" prop="slug">
          <el-input v-model="temp.slug" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="temp.icon" />
        </el-form-item>
        <el-form-item label="背景图片" prop="background">
          <el-input v-model="temp.background" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { feachList, saveOrUpdate, del } from '@/api/category'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import { mapGetters } from 'vuex'
export default {
  name: 'Category',
  components: {
    Pagination
  },
  data() {
    return {
      listLoading: false,
      tableKey: 0,
      total: 0,
      list: [],
      statusMap: {
        true: '启用',
        false: '禁用'
      },
      listQuery: {
        page: 1,
        limit: 10
      },
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        update: '修改',
        create: '添加'
      },
      temp: {},
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'change' }],
        slug: [{ required: true, message: '英文名称不能为空', trigger: 'change' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'change' }],
        icon: [{ required: true, message: '图标不能为空', trigger: 'change' }],
        background: [{ required: true, message: '背景图片不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'SiteSettings'
    ])
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      const { result } = await feachList(this.listQuery)
      this.listLoading = false
      this.list = result.list
      this.total = result.total
      console.info(result)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.temp = {}
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    message(title, type, message) {
      this.$notify({
        title: title,
        message: message,
        type: type,
        duration: 2000
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveOrUpdate(this.temp).then(res => {
            if (res.code === 0) {
              this.message('添加分类', 'success', res.message)
              this.dialogFormVisible = false
              this.handleFilter()
              this.$store.dispatch('category/getCategoryList')
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveOrUpdate(this.temp).then(res => {
            if (res.code === 0) {
              this.message('修改分类', 'success', res.message)
              this.dialogFormVisible = false
              this.handleFilter()
              this.$store.dispatch('category/getCategoryList')
            }
          })
        }
      })
    },
    handleDelete(row) {
      MessageBox.confirm(`是否确认删除【${row.name}】这条数据？`, '删除', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row.id).then(res => {
          if (res.code === 0) {
            this.message('删除分类', 'success', res.message)
            this.dialogFormVisible = false
            this.handleFilter()
            this.$store.dispatch('category/getCategoryList')
          }
        })
      })
    }
  }
}
</script>
